(function () {
    var imgs = document.getElementById('imgs'),
        menu = document.getElementById('menu'),
        duration = 2000,
        imgDom = [], //图片节点集合
        navDOM = [], //导航节点集合
        activeImg = null, //选中的图片
        activeNav = null; //选中的导航


    for (var i = 0; i < data.length; i++) {
        var item = data[i]

        // 生成图片
        var tagI = document.createElement('a')
        tagI.setAttribute('href', '#')
        tagI.style.backgroundImage = `url(${item.img})`
        tagI.style.backgroundColor = `${item.bg}`
        imgs.appendChild(tagI)
        imgDom.push(tagI)
        // 生成导航
        var tagN = document.createElement('a')
        tagN.setAttribute('href', '#')
        tagN.setAttribute('class', 'nav')
        tagN.setAttribute('title', `${item.title}:${item.desc}`)
        tagN.innerHTML = `<span>${item.title}</span>${item.desc}}`
        menu.appendChild(tagN)
        navDOM.push(tagN)

        if (i == 0) {
            tagI.setAttribute('class', 'active')
            tagN.setAttribute('class', 'active')
            activeImg = tagI
            activeNav = tagN
        }

        tagN.onmouseenter = (function (tagI, tagN) {
            return function () {
                clearInterval(timerId)
                // 移除样式
                activeImg.setAttribute('class', '')
                activeNav.setAttribute('class', 'nav')

                // 重新添加样式
                tagI.setAttribute('class', 'active')
                tagN.setAttribute('class', 'active')

                // 记录选中的节点
                activeImg = tagI
                activeNav = tagN
            }
        })(tagI, tagN)

        // 移除开启定时器
        tagN.onmouseleave = function () {
            timerId = setInterval(move, duration);
        }

    }
    var timerId = setInterval(move, duration);

    function move() {
        activeImg.setAttribute('class', '')
        activeNav.setAttribute('class', 'nav')

        var index = imgDom.indexOf(activeImg)
        if (index === imgDom.length - 1) {
            activeImg = imgDom[0]
            activeNav = navDOM[0]
        } else {
            activeImg = imgDom[index + 1]
            activeNav = navDOM[index + 1]
        }
        activeImg.setAttribute('class', 'active')
        activeNav.setAttribute('class', 'active')
      }
})()